<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/Welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 分栏间隔 -->
      <el-row :gutter="10">
        <el-col :span="6">
          <div class="grid-content bg-purple">
            <!-- 搜索与添加 -->
            <div>
              <el-input placeholder="请输入内容" v-model="users.query">
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="userList()"
                ></el-button>
              </el-input>
            </div>
          </div>
        </el-col>
        <!-- 添加 -->
        <el-col :span="6">
          <div class="grid-content bg-purple">
            <el-button type="primary" round @click="dialogVisible = true"
              >添加用户</el-button
            >
          </div>
        </el-col>
      </el-row>
      <!--用户的信息 -->
      <!-- table表格 -->
      <el-table border style="width: 100%" :data="userData">
        <el-table-column type="index" label="#" width="50"> </el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="address" label="状态">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <!-- switch开关 -->
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="userChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作" width="180">
          <!-- 使用作用域插槽 -->
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="edit(scope.row)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delet(scope.row.id)"
            ></el-button>
            <!-- 用户分配 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="用户分配"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-s-tools"
                size="mini"
                @click="Role(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页效果 -->
      <el-pagination
        @current-change="handleCurrentChange"
        :page-size="users.pagesize"
        layout="total, prev, pager, next"
        :total="total"
        background
      >
      </el-pagination>
      <!-- 添加用户 -->
      <el-dialog
        title="添加用户"
        :visible.sync="dialogVisible"
        width="40%"
        @close="dianlogClose"
      >
        <!-- 表单 -->
        <el-form
          :model="addUserForm"
          :rules="addUserRules"
          ref="addUserRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <!-- 用户名 -->
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username"></el-input>
          </el-form-item>
          <!-- 密码 -->
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUserForm.password" type="password"></el-input>
          </el-form-item>
          <!-- 邮箱 -->
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email"></el-input>
          </el-form-item>
          <!-- 手机号 -->
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="addUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 表单 -->

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑用户信息 -->
      <el-dialog
        title="编辑用户信息"
        :visible.sync="editDialog"
        width="40%"
        @close="dianlogClose"
      >
        <!-- 表单 -->
        <el-form
          :model="edits"
          :rules="addUserRules"
          ref="addUserRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <!-- 用户名 -->
          <el-form-item label="用户名" prop="username">
            <el-input v-model="edits.username" disabled></el-input>
          </el-form-item>

          <!-- 邮箱 -->
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="edits.email"></el-input>
          </el-form-item>
          <!-- 手机号 -->
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="edits.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 表单 -->

        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialog = false">取 消</el-button>
          <el-button type="primary" @click="editUser">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
    <!-- 分配角色的弹框 -->
    <el-dialog
      title="提示"
      :visible.sync="dialogRole"
      width="30%"
      @close="rolesClose"
    >
      <p>当前用户：{{ Roles.username }}</p>
      <p>当前角色：{{ Roles.role_name }}</p>
      <!-- select选择器 -->
      <el-select v-model="roleId" placeholder="请选择">
        <el-option
          v-for="item in RoleInfo"
          :key="item.id"
          :label="item.roleName"
          :value="item.id"
        >
        </el-option>
      </el-select>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogRole = false">取 消</el-button>
        <el-button type="primary" @click="saveRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import http from '../util/http.js'
export default {
  data () {
    // 定义一个手机号的验证规则
    var cheakMobile = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        // 合法的手机号
        return callback()
      }
      callback(new Error('请输入合法的手机号'))
    }
    return {
      userData: [],
      // 请求数据需要传的数据
      users: {
        query: '', // 查询的参数,
        pagenum: 1, // 当前的页码
        pagesize: 5 // 一页显示都是条数据
      },
      total: 0, // 总数
      // 添加弹出框的显示隐藏
      dialogVisible: false,
      // 编辑用户弹出框
      editDialog: false,
      // 分配角色的弹框
      dialogRole: false,
      // 编辑用户的数据
      edits: {},
      // 分配角色信息
      Roles: {
        username: '',
        role_name: '',
        id: ''
      },
      // 分配的信息
      RoleInfo: [],
      // 存放select的权限id
      roleId: '',
      // 表单绑定的值
      addUserForm: {
        email: '',
        username: '',
        password: '',
        mobile: ''
      },
      // 验证添加表单
      addUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 10,
            message: '长度在 6 到 10 个字符',
            trigger: 'blur'
          }
        ],

        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur']
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          },
          {
            validator: cheakMobile,
            message: '请输入正确的手机号',
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },
  mounted () {
    // 请求用户的数据
    this.userList()
  },

  methods: {
    // 修改用户
    edit (val) {
      // console.log(val);
      http(`users/${val.id}`).then((res) => {
        // console.log(res.data.data.id);
        this.edits = res.data.data
        // console.log(this.edits.id);
      })
      this.editDialog = true
    },
    // 确定修改用户
    editUser () {
      this.editDialog = false
      // console.log(this.edits.id);
      http({
        url: `users/${this.edits.id}`,
        method: 'put',
        data: this.edits
      }).then((res) => {
        console.log(res.data)
        if (res.data.meta.status) {
          // console.log(1);
          this.$message.success('修改成功')
          this.userList()
        } else {
          this.$message.error('修改失败')
        }
      })
    },
    // 修改用户的状态
    userChange (val) {
      // console.log(val);
      http({
        url: `users/${val.id}/state/${val.mg_state}`,
        method: 'put'
      }).then((res) => {
        // console.log(res.data.meta.status);
        if (res.data.meta.status === 200) {
          // console.log("设置成功");
          this.$message.success('更改状态成功')
        } else {
          val.mg_state = !val.mg_state
          this.$message.error('更改状态失败')
        }
      })
    },

    // 用户列表
    userList () {
      http({
        url: 'users',
        params: this.users,
        method: 'get'
      }).then((res) => {
        console.log(res.data.data)
        this.userData = res.data.data.users
        this.total = res.data.data.total
      })
    },
    // 分页效果
    handleCurrentChange (val) {
      // console.log(val);
      this.users.pagenum = val
      this.userList()
    },
    // 关闭添加用户的框的时候清除表单数据
    dianlogClose () {
      // 清空表单
      this.$refs.addUserRef.resetFields()
    },
    // 添加用户
    addUser () {
      this.dialogVisible = false

      // 通过表单预验证看看是否验证成功 在表单中绑定ref 根据文档通过 validate回调函数进行验证
      this.$refs.addUserRef.validate((val) => {
        if (val) {
          // console.log(this.addUserForm);

          http({
            method: 'post',

            url: 'users',

            data: this.addUserForm
          }).then((res) => {
            // console.log(res.data.meta.status);
            if (res.data.meta.status === 201) {
              this.$message.success('添加成功')
              this.userList()
            } else {
              this.$message.error('添加失败')
            }
          })
        }
      })
    },
    // 删除用户
    delet (id) {
      const c = confirm('确定要删除次用户吗')
      if (c) {
        http.delete(`users/${id}`).then((res) => {
          // console.log(res);
          if (res.data.meta.status === 200) {
            this.$message.success('删除成功')
            this.userList()
          } else {
            this.$message.error('删除失败')
          }
        })
      } else {
        this.$message.error('已取消删除')
      }
    },
    // 分配角色
    Role (row) {
      console.log(row)
      this.Roles.username = row.username
      this.Roles.role_name = row.role_name
      this.Roles.id = row.id
      // 请求role的全部数据
      http('roles').then((res) => {
        console.log(res.data.data)
        this.RoleInfo = res.data.data
      })
      // console.log(this.roleName);
      this.dialogRole = true
    },
    // 确定分配角色
    saveRole () {
      http({
        url: `users/${this.Roles.id}/role`,
        data: { rid: this.roleId },
        method: 'put'
      }).then((res) => {
        // console.log(res);
        if (res.data.meta.status === 200) {
          this.$message.success('设置成功')
        }
        this.$message.error('设置失败')
        this.userList()
      })
      this.dialogRole = false
    },

    // 关闭分配的时候
    rolesClose () {
      this.RoleInfo = {}
      this.roleId = ''
    }
  }
}
</script>
